class Events { // 发布订阅者模式

	static instance = null;

	static get event() {
		if (!this.instance) {
			this.instance = new Events()
		}
		return this.instance
	}

	constructor() {
		this.events = new Map()
	}

	addEvent(key, fn, isOnce = false, ...arg) {
		const value = this.events.get(key) ? this.events.get(key) : this.events.set(key, new Map()).get(key)
		value.set(fn, (...arg1) => {
			fn(...arg, ...arg1)
			isOnce && this.off(key, fn)
		})
		console.log("订阅成功");
	}

	on(key, fn, ...args) {
		if (typeof fn !== "function") {
			throw "fn must be a function"
			return
		}
		this.addEvent(key, fn, false, ...args)
	}

	emit(key, ...args) {
		if (!this.events.get(key)) {
			console.warn(`没有 ${key} 事件`)
			return
		}
		for (let [, cb] of this.events.get(key).entries()) {
			cb(...args)
		}
	}

	off(key, fn) {
		if (this.events.get(key)) {
			if (typeof fn === "function") {
				this.events.get(key).delete(fn)
			} else if (fn === null) {
				this.events.delete(key)
			}
		}
	}

	once(key, fn, ...args) {
		this.addEvent(key, fn, true, ...args)
	}

}

export {Events}
